import React, { useState, useEffect } from "react";
import styles from "../style/me.module.css";
import { useNavigate } from "react-router-dom";
import {home} from "../api/home";
// 图片导入
import avatar from "../img/t1.png";
import gradeIcon from "../img/MEjifen.png";
import rightArrow from "../img/right.png";
// 底部导航栏图片
import navIcon1 from "../img/ones.png";
import navIcon2 from "../img/fours.png";
import navIcon3 from "../img/10019.png";
import navIcon4 from "../img/twos.png";
import navIcon5 from "../img/three.png";
import biudifou from "../img/biudifou.jpg";
import shezhi from "../img/shezhi.png";
import oye from "../img/Oye.png";
import love from '../img/love.png'

const MePage = () => {
  interface Product {
    id: number;
    title?: string;
    synopsis?: string;
    price: number | string;
    original_price?: number | string;
    img?: string;
  }
  interface ApiResponse {
    data: {
      list?: Product[];
    };
  }
  const navigate = useNavigate();
  const [shopList, setShopList] = useState<Product[]>([]);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");

  useEffect(() => {
    fetchShopList();
  }, []);

  // 为你推荐列表

    const fetchShopList = async () => {
      try {
        // 检查 user.data 是否存在
        if (!user?.data?.token || !user?.data?.id) {
          console.error("用户数据不存在或 token/id 为空");
          return;
        }

        // 发送请求
        const res = await home({
          headers: {
            token: user.data.token,
            id: user.data.id,
          },
        });
        console.log("请求结果:", res);

        // 检查返回数据
        if (res.data && Array.isArray(res.data.data.list)) {
          setShopList(res.data.data.list);
        } else {
          console.error("返回数据格式不符合预期:", res.data);
          setShopList([]);
        }
      } catch (error) {
        console.error("获取推荐商品失败:", error);
      }
    };

  const handleItemClick = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    navigate("/detail");
  };

  const handleCollect = () => {
    // 处理收藏跳转逻辑
    navigate("/collect");
  };

  const handleAddress = () => {
    // 处理地址跳转逻辑
    navigate("/address");
  };
  // 跳转到我的足迹
  function handleFootprint() {
    // 处理足迹跳转逻辑
    navigate("/footprint");
  }

  return (
    <div className={styles.container}>
      {/* 顶部个人信息区域 - 使用新背景图 */}
      <div className={styles.topSection}>
        <div className={styles.profileHeader}>
          <div className={styles.profileContainer}>
            <div className={styles.avatarContainer}>
            <img src={biudifou} alt="头像" className={styles.avatar} />
          </div>
          <div className={styles.profileInfo}>
            <div className={styles.nameRow}>
              <h3>刘晗语</h3>
              <img src={gradeIcon} alt="等级" className={styles.gradeIcon} />
              <span className={styles.points}>当前积分 1000分</span>
              <img
                src={shezhi}
                alt="设置"
                onClick={() => navigate("/quit")}
                className={styles.moreIcon}
              />
            </div>
            <p className={styles.title}>三级特级教师</p>
          </div>
          </div>
          {/* 数据统计 */}
          <div className={styles.statsContainer}>
            {["商品收藏", "浏览足迹", "优惠券"].map((item, index) => (
              <React.Fragment key={item}>
                <div
                  className={styles.statItem}
                  onClick={() => {
                    if (index === 0) handleCollect();
                    else if (index === 1) handleFootprint();
                    else if (index === 2) navigate("/coupon");
                  }}
                >
                  <div className={styles.statNumber}>1</div>
                  <div className={styles.statLabel}>{item}</div>
                </div>
                {index < 2 && <div className={styles.divider} />}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* 功能入口 */}
        <div className={styles.featuresGrid}>
          {[
            {
              icon: "scoreGuan.png",
              label: "积分管理",
              onClick: () => navigate("/score"),
            },
            {
              icon: "youhuijuan.png",
              label: "优惠券",
              onClick: () => navigate("/coupon"),
            },
            { icon: "shdz.png", label: "收货地址", onClick: handleAddress },
            {
              icon: "clockMe.png",
              label: "打卡",
              onClick: () => navigate("/clock"),
            },
            {
              icon: "xueyuan.png",
              label: "学员管理",
              onClick: () => navigate("/student"),
            },
          ].map((item) => (
            <div
              key={item.label}
              className={styles.featureItem}
              onClick={item.onClick}
            >
              <div className={styles.featureIcon}>
                <img src={require(`../img/${item.icon}`)} alt={item.label} />
              </div>
              <p>{item.label}</p>
            </div>
          ))}
        </div>

        {/* 我的订单 */}
        <div className={styles.orderSection}>
          <div
            className={styles.sectionHeader}
            onClick={() => navigate("/orders")}
          >
            <h4>我的订单</h4>
            <img src={rightArrow} alt="查看全部" />
          </div>
          <div className={styles.orderStatus}>
            {[
              {
                icon: "dfk.png",
                label: "待付款",
                onClick: () => navigate("/orders?status=1"),
              },
              {
                icon: "dfh.png",
                label: "待发货",
                onClick: () => navigate("/orders?status=2"),
              },
              {
                icon: "dsh.png",
                label: "待收货",
                onClick: () => navigate("/orders?status=3"),
              },
              {
                icon: "dpj.png",
                label: "待评价",
                onClick: () => navigate("/orders?status=4"),
              },
            ].map((item) => (
              <div
                key={item.label}
                onClick={item.onClick}
                className={styles.statusItem}
              >
                <img src={require(`../img/${item.icon}`)} alt={item.label} />
                <p>{item.label}</p>
              </div>
            ))}
          </div>
        </div>

        {/* 签到赢积分 - 使用新背景图 */}
        <div className={styles.signSection}>
          <div className={styles.signBanner} onClick={() => navigate("/clock")}>
            <img
              src={oye}
              alt=""
            />
          </div>
        </div>

        <div className={styles.three}>
          <img
            src={love}
            alt=""
          />
          <p>猜你喜欢</p>
        </div>
        {/* 推荐商品保持原有属性名 */}
        <div className={styles.recommend}>
          <div className={styles.shop}>
            {shopList.map((product) => (
              <div
                key={product.id}
                className={styles.shop_item}
                onClick={() => handleItemClick(product.id)}
              >
                <img
                  src={product.img || "../img/head.jpg"}
                  alt={product.title || "商品"}
                />
                <p>{product.title || "商品名称"}</p>
                <span>{product.synopsis || "商品描述"}</span>
                <div className={styles.items}>
                  <p>￥{Number(product.price).toFixed(2)}</p>
                  {typeof product.original_price === "number" && (
                    <del>￥{product.original_price.toFixed(2)}</del>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className={styles.three}>
          <div></div>
          <p>为您推荐</p>
          <div></div>
        </div>

        {/* 底部导航栏（保持不变） */}
        <div className={styles.bottom}>
          <div className={styles.bottom_item} onClick={() => navigate("/home")}>
            <div>
              <img src={navIcon1} alt="首页" />
            </div>
            <p>首页</p>
          </div>
          <div
            className={styles.bottom_item}
            onClick={() => {
              localStorage.setItem("id", "99");
              navigate("/classify");
            }}
          >
            <div>
              <img src={navIcon2} alt="分类" />
            </div>
            <p>分类</p>
          </div>
          <div className={styles.punch} onClick={() => navigate("/clock")}>
            <div>
              <div className={styles.punches}>
                <div className={styles.punchs}>
                  <img src={navIcon3} alt="打卡" />
                </div>
              </div>
            </div>
            <p>打卡</p>
          </div>
          <div
            className={styles.bottom_item}
            onClick={() => navigate("/shopcart")}
          >
            <div>
              <img src={navIcon4} alt="购物车" />
            </div>
            <p>购物车</p>
          </div>
          <div className={styles.bottom_items}>
            <div>
              <img src={navIcon5} alt="我的" />
            </div>
            <p>我的</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MePage;
